package com.dwxt.mall.service;

import com.dwxt.common.base.YesOrNo;
import com.dwxt.common.util.PartyUtil;
import com.dwxt.mall.dao.ReceiptAddressMapper;
import com.dwxt.mall.entity.ReceiptAddress;
import com.dwxt.mall.entity.ReceiptAddressExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressService {

    @Autowired
    private ReceiptAddressMapper receiptAddressMapper;

    public void createOrUpdateAddress(ReceiptAddress receiptAddress) {
        String userId = PartyUtil.getCurrentUserId();
        if (receiptAddress.getIsDefault() == YesOrNo.YES) {
            //把所有默认地址置为否
            updateAddressToNotDefault(userId);
        }
        if (receiptAddress.getId() != null) {
            receiptAddressMapper.updateByPrimaryKeySelective(receiptAddress);
        } else {
            receiptAddress.setUserId(userId);
            receiptAddressMapper.insertSelective(receiptAddress);
        }
    }

    private void updateAddressToNotDefault(String userId) {
        ReceiptAddress address = new ReceiptAddress();
        address.setIsDefault(YesOrNo.NO);
        ReceiptAddressExample example = new ReceiptAddressExample();
        example.createCriteria().andUserIdEqualTo(userId).andIsDefaultEqualTo(YesOrNo.YES);
        receiptAddressMapper.updateByExampleSelective(address, example);
    }

    public List<ReceiptAddress> selectAllAddress() {
        String userId = PartyUtil.getCurrentUserId();
        ReceiptAddressExample example = new ReceiptAddressExample();
        example.createCriteria().andUserIdEqualTo(userId);
        example.setOrderByClause("create_time desc");
        return receiptAddressMapper.selectByExample(example);
    }

    public ReceiptAddress selectDefaultAddress() {
        String userId = PartyUtil.getCurrentUserId();
        ReceiptAddressExample example = new ReceiptAddressExample();
        example.createCriteria().andUserIdEqualTo(userId).andIsDefaultEqualTo(YesOrNo.YES);
        List<ReceiptAddress> addressList = receiptAddressMapper.selectByExample(example);
        if (addressList.size() > 0) {
            return addressList.get(0);
        } else {
            example.clear();
            example.createCriteria().andUserIdEqualTo(userId);
            example.setOrderByClause("create_time desc");
            addressList = receiptAddressMapper.selectByExample(example);
            if (addressList.size() > 0) {
                return addressList.get(0);
            } else {
                return null;
            }
        }
    }

    public void delete(Integer id) {
        receiptAddressMapper.deleteByPrimaryKey(id);
    }

    public ReceiptAddress selectByKey(Integer id) {
        return receiptAddressMapper.selectByPrimaryKey(id);
    }
}
